﻿@page "/项目执行进展"
@layout MainLayout2
@using BootstrapBlazor
@rendermode InteractiveServer
@inject ToastService ToastService
@inject AuthenticationStateProvider customAuthenticationStateProvider
@inject SqlSugarScope _SqlSugarScope
@inject NavigationManager NavigationManager

    <h3>项目执行进展</h3>
    <h3>计量单位:万元</h3>

@* <div class="row g-3">
    <div class="col-12 col-sm-6">
        <BootstrapInput PlaceHolder="项目名称" @bind-Value="@bus.项目名称"
                        DisplayText="项目名称" ShowLabel="true" />
    </div>
</div>
<div class="row g-3">
    <div class="col-12 col-sm-6">
        <BootstrapInput PlaceHolder="档案编号" @bind-Value="@bus.档案编号"
                        ShowLabel="true"
                        DisplayText="档案编号" />
    </div>
    <Button Icon="fa-solid fa-arrows-rotate" Text="刷新" OnClick="OnClick" class="col-12 col-sm-auto" />
</div> *@

<Table RenderMode="TableRenderMode.Table" TItem="View合同执行情况" IsStriped="true" IsBordered="true"
       IsPagination="true" PageItemsSource="@PageItemsSource" OnQueryAsync="@OnQueryAsync"
       ShowSearch="true" SearchMode="SearchMode.Top"
       IsFixedHeader="true">
    <TableColumns>
        <TableColumn Width="80" Fixed="true" TextEllipsis="true" @bind-Field="@context.项目经理" />
        <TableColumn Width="80" Fixed="true" TextEllipsis="true" @bind-Field="@context.档案编号" />
        <TableColumn Width="200" Fixed="true" TextEllipsis="true" @bind-Field="@context.项目名称" />
        <TableColumn Width="100" FormatString="yyyy-MM-dd" @bind-Field="@context.工期开始" />
        <TableColumn Width="100" FormatString="yyyy-MM-dd" @bind-Field="@context.验收日期" />
        <TableColumn Width="100" FormatString="yyyy-MM-dd" Text="竣工日期" @bind-Field="@context.工期开始" />
        <TableColumn Width="80" Text="施工产值" @bind-Field="@context.已完成产值" Formatter="@IntFormatter" />
        <TableColumn Width="80" FormatString="P" Text="完工进度" @bind-Field="@context.完工进度" />
        <TableColumn Width="80" Text="合同造价" @bind-Field="@context.合同价" Formatter="@IntFormatter" />
        <TableColumn Width="80" Text="审定值" @bind-Field="@context.审定价" Formatter="@IntFormatter" />
        <TableColumn Width="80" Text="已开票" @bind-Field="@context.已开票" Formatter="@IntFormatter" />
        <TableColumn Width="80" Text="已收款" @bind-Field="@context.已收" Formatter="@IntFormatter" />
        <TableColumn Width="80" Text="未收款" @bind-Field="@context.未收" Formatter="@IntFormatter" />
        <TableColumn Width="80" Text="未开票" @bind-Field="@context.未开票" Formatter="@IntFormatter" />
        <TableColumn Width="80" FormatString="P" Text="开票进度%" @bind-Field="@context.开票进度" />
        <TableColumn Width="80" FormatString="P" Text="收款进度%" @bind-Field="@context.收款进度" />
        <TableColumn Width="200" TextEllipsis="true" FormatString="P" Text="合同支付条款" @bind-Field="@context.合同摘要" />
    </TableColumns>
    <SearchTemplate>
        <GroupBox Title="搜索条件">
            <div class="row g-3 form-inline">
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.档案编号" PlaceHolder="档案编号" maxlength="50" ShowLabel="true" DisplayText="档案编号" />
                </div>
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.项目名称" PlaceHolder="项目名称" maxlength="500" ShowLabel="true" DisplayText="项目名称" />
                </div>
            </div>
        </GroupBox>
    </SearchTemplate>
</Table>

@code {

    [NotNull]
    private List<View合同执行情况>? Items { get; set; }

    private Bus_合同主表 bus = new Bus_合同主表();

    bool IsAutoRefresh = false;

    private static IEnumerable<int> PageItemsSource => new int[]
       {
        5,
        10,
        20,
        40,
        80,
        100
       };

    protected override async Task OnInitializedAsync()
    {
        查询();
    }

    private void OnClick()
    {
        查询();
    }


    protected Task<string> IntFormatter(object? d)
    {
        var ret = "";
        if (d is TableColumnContext<View合同执行情况, object?> data && data.Value != null)
        {
            var val = (decimal)data.Value/10000;
            ret = val.ToString("0.00");
        }
        return Task.FromResult(ret);
    }
    private void 查询()
    {

        //     //塞入View合同执行情况
        string guid = Guid.NewGuid().ToString();
        //     string sql = $@"insert into [dbo].[View合同执行情况] ([guid], [合同主表guid], [档案编号], [签订日期], [项目经理], [合同状态], [项目分类], [项目名称], [甲方单位], [中标通知书], [合同份数], [竣工验收证明], [审计报告], [工期开始], [工期结束], [履约保证金], [合同价], [审定价], [已完成产值], [完工进度], [验收日期], [审计日期], [已开票], [已收], [未收], [未开票], [开票进度], [收款进度], [合同摘要], [自建成本], [分包成本], [项目毛利], [项目利润率])
        //                         select '{guid}',* from View_合同执行情况";
        //     _SqlSugarScope.Ado.ExecuteCommand(sql);

        //     sql = $@"
        //                   update View合同执行情况 set 非周期产值 = t.产值
        //                   from View合同执行情况,(select 总包合同ID,sum(经理作业量*项目任务明细含税单价) 产值
        // 		                    from Bus_合同分拆报工 
        // 		                    where 分拆状态 = '项目经理审核' and   exists(select bguid from Bus_项目任务明细 where  (结算类型 <> '周期' or 结算类型 is null) and 已失效 = 0 and 项目任务明细ID = bguid)
        // 		                    group by 总包合同ID) t
        //                           where guid = '{guid}'
        //                   and t.总包合同ID = View合同执行情况.合同主表guid

        //                   update View合同执行情况 set 周期产值 =  t.prorated_amount
        //                   from View合同执行情况, (
        //                 SELECT
        //                 guid,
        //                 sum(
        //                     含税单价 * (DATEDIFF(DAY, 
        //                              CASE WHEN 结算开始日期 < '2000-01-01' THEN '2000-01-01' ELSE 结算开始日期 END, 
        //                              CASE WHEN 结算结束日期 > GETDATE() THEN GETDATE() ELSE 结算结束日期 END) + 1)) AS prorated_amount
        //                 FROM Bus_项目任务明细
        //                 WHERE 1=1
        //                 and 结算开始日期 <= GETDATE() AND 结算结束日期 >= '2000-01-01'
        //                 and  结算类型 = '周期' and 已失效 = 0
        //                 group by guid
        //                 )t
        //                           where View合同执行情况.guid = '{guid}'
        //                   and  t.guid = View合同执行情况.合同主表guid


        //                   update View合同执行情况 set 已完成产值 = isnull(非周期产值,0) + isnull(周期产值,0)
        //                           where View合同执行情况.guid = '{guid}'";

        //     _SqlSugarScope.Ado.ExecuteCommand(sql);


        //     sql = $@" update View合同执行情况 set 未开票 = 审定价-isnull(已开票,0)	,开票进度 = isnull(已开票,0)/审定价,收款进度 = isnull(已收,0)/已开票
        //               where guid = '{guid}'
        //               and 审定价 > 0

        //                 update View合同执行情况 set 未开票 = 合同价-已开票	,开票进度 = 已开票/合同价
        //               where guid = '{guid}'
        //               and 合同价 > 0";

        // _SqlSugarScope.Ado.ExecuteCommand(sql);
        更新合同产值(guid,null,null);
        Items = _SqlSugarScope.Queryable<View合同执行情况>()
                                         .Where(it => it.guid == Guid.Parse(guid))
                                         .WhereIF(!string.IsNullOrEmpty(bus.项目名称), it => it.项目名称.Contains(bus.项目名称))
                                         .WhereIF(!string.IsNullOrEmpty(bus.档案编号), it => it.项目名称.Contains(bus.档案编号))
                                        .OrderBy(it => it.项目经理)
                                        .ToList();
    }

    private Task<QueryData<View合同执行情况>> OnQueryAsync(QueryPageOptions options)
    {
        IEnumerable<View合同执行情况> items = Items;
        View合同执行情况 mode = (options.SearchModel as View合同执行情况);


            items = items
                .WhereIF(!string.IsNullOrEmpty(mode?.档案编号), it => it.档案编号.Contains(mode.档案编号))
                 .WhereIF(!string.IsNullOrEmpty(mode?.项目名称), it => it.项目名称.Contains(mode.项目名称))
                 .ToList();
        
        var total = items.Count();
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();
        return Task.FromResult(new QueryData<View合同执行情况>() { Items = items, TotalCount = total, IsSorted = true, IsFiltered = true, IsSearch = true });
    }

    public  int 更新合同产值(string guid, DateTime? dateEdit开始, DateTime? dateEdit结束)
    {
        if (dateEdit开始 == null)
        {
            dateEdit开始 = new DateTime(2000, 1, 1);
        }
        if (dateEdit结束 == null)
        {
            dateEdit结束 = DateTime.Now;
        }

        //塞表
        string sql = $@"insert into [dbo].[View合同执行情况] ([guid], [合同主表guid], [档案编号], [签订日期], [项目经理], [合同状态], [项目分类], [项目名称], [甲方单位], [中标通知书], [合同份数], [竣工验收证明], [审计报告], [工期开始], [工期结束], [履约保证金], [合同价], [审定价], [已完成产值], [完工进度], [验收日期], [审计日期], [已开票], [已收], [未收], [未开票], [开票进度], [收款进度], [合同摘要], [自建成本], [分包成本], [项目毛利], [项目利润率])
                            select '{guid}',* from View_合同执行情况";
        _SqlSugarScope.Ado.ExecuteCommand(sql);

        //更新产值
        sql = $@"
                      update View合同执行情况 set 非周期产值 = t.产值
                      from View合同执行情况,(select 总包合同ID,sum(经理作业量*项目任务明细含税单价) 产值
						                    from Bus_合同分拆报工
						                    where 分拆状态 = '项目经理审核' and   exists(select bguid from Bus_项目任务明细 where  (结算类型 <> '周期' or 结算类型 is null)
                                            and 已失效 = 0 and 项目任务明细ID = bguid
                                            and 施工开始时间 > = '{dateEdit开始}' and 施工开始时间 < '{dateEdit结束?.AddDays(1).Date}'
                                            )
						                    group by 总包合同ID) t
                              where guid = '{guid}'
                      and t.总包合同ID = View合同执行情况.合同主表guid

                      update View合同执行情况 set 周期产值 =  t.prorated_amount
                      from View合同执行情况, (
                    SELECT
                    guid,
                    sum(
                        含税单价 * (DATEDIFF(DAY,
                                 CASE WHEN 结算开始日期 < '{dateEdit开始}' THEN '{dateEdit开始}' ELSE 结算开始日期 END,
                                 CASE WHEN 结算结束日期 > '{dateEdit结束?.Date}' THEN GETDATE() ELSE 结算结束日期 END) + 1)) AS prorated_amount
                    FROM Bus_项目任务明细
                    WHERE 1=1
                    and 结算开始日期 <= '{dateEdit结束?.Date}' AND 结算结束日期 >= '{dateEdit开始}'
                    and  结算类型 = '周期' and 已失效 = 0
                    group by guid
                    )t
                              where View合同执行情况.guid = '{guid}'
                      and  t.guid = View合同执行情况.合同主表guid
                    ";

        //更新产值 完工进度
        sql += $@"update View合同执行情况 set 已完成产值 = isnull(非周期产值,0) + isnull(周期产值,0)
                              where View合同执行情况.guid = '{guid}';

                      update View合同执行情况 set 完工进度 = 已完成产值 / 审定价
                        where isnull(审定价,0) > 0;
                    update View合同执行情况 set 完工进度 = 已完成产值 / 合同价
                                            where isnull(合同价,0) > 0 and isnull(审定价,0) <= 0;";

        // 开票进度
        sql += $@" update View合同执行情况 set 未开票 = 审定价-isnull(已开票,0)	,开票进度 = isnull(已开票,0)/审定价,收款进度 = isnull(已收,0)/已开票
                  where guid = '{guid}'
                  and isnull(审定价,0) > 0

                    update View合同执行情况 set 未开票 = 合同价-已开票	,开票进度 = 已开票/合同价
                  where guid = '{guid}'
                  and isnull(合同价,0) > 0 and isnull(审定价,0) <= 0
            ";

        //收款进度
        sql += $@" update View合同执行情况 set 收款进度 = isnull(已收,0)/已开票
                  where guid = '{guid}'
                  and isnull(已开票,0) > 0";

        return _SqlSugarScope.Ado.ExecuteCommand(sql);
    }

}
